<?php

namespace Kunfeng\Dify\Model\Completion;

use Kunfeng\Dify\Model\Common\Metadata;

/**
 * 文本生成响应模型
 */
class CompletionResponse
{
    private $messageId;
    private $mode;
    private $answer;
    private $metadata;
    private $createdAt;

    public function __construct(
        string $messageId,
        string $mode,
        string $answer,
        ?Metadata $metadata = null,
        ?int $createdAt = null
    ) {
        $this->messageId = $messageId;
        $this->mode = $mode;
        $this->answer = $answer;
        $this->metadata = $metadata;
        $this->createdAt = $createdAt;
    }

    /**
     * 从数组创建响应
     */
    public static function fromArray(array $data): self
    {
        return new self(
            $data['message_id'] ?? '',
            $data['mode'] ?? '',
            $data['answer'] ?? '',
            isset($data['metadata']) ? Metadata::fromArray($data['metadata']) : null,
            $data['created_at'] ?? null
        );
    }

    /**
     * 转换为数组
     */
    public function toArray(): array
    {
        $data = [
            'message_id' => $this->messageId,
            'mode' => $this->mode,
            'answer' => $this->answer,
        ];

        if ($this->metadata !== null) {
            $data['metadata'] = $this->metadata->toArray();
        }
        if ($this->createdAt !== null) {
            $data['created_at'] = $this->createdAt;
        }

        return $data;
    }

    public function getMessageId(): string
    {
        return $this->messageId;
    }

    public function getMode(): string
    {
        return $this->mode;
    }

    public function getAnswer(): string
    {
        return $this->answer;
    }

    public function getMetadata(): ?Metadata
    {
        return $this->metadata;
    }

    public function getCreatedAt(): ?int
    {
        return $this->createdAt;
    }
}
